import mongoose, { Document, Schema } from 'mongoose';

export interface IDevice extends Document {
  deviceId: string;
  name: string;
  type: string;
  status: 'online' | 'offline';
  lastHeartbeat: Date;
  userId: mongoose.Types.ObjectId;
  temperature?: number;
  humidity?: number;
  password: string;
  createdAt: Date;
  updatedAt: Date;
  config?: {
    samplingInterval: number;
    uploadInterval: number;
    firmwareVersion?: string;
    alarmThresholds: {
      temperature: {
        high: number;
        low: number;
      };
      humidity: {
        high: number;
        low: number;
      };
    };
    wifi?: {
      ssid: string;
      password: string;
      signalStrength?: number;
    };
    mqtt?: {
      server: string;
      username: string;
      password: string;
    };
  };
}

const deviceSchema = new Schema({
  deviceId: {
    type: String,
    required: true,
    unique: true,
  },
  name: {
    type: String,
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
  status: {
    type: String,
    enum: ['online', 'offline'],
    default: 'offline',
  },
  lastHeartbeat: {
    type: Date,
    default: Date.now,
  },
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
  temperature: {
    type: Number,
  },
  humidity: {
    type: Number,
  },
  password: {
    type: String,
    required: true,
  },
  config: {
    samplingInterval: { type: Number, default: 60 },
    uploadInterval: { type: Number, default: 300 },
    firmwareVersion: { type: String },
    alarmThresholds: {
      temperature: {
        high: { type: Number, default: 30 },
        low: { type: Number, default: 10 }
      },
      humidity: {
        high: { type: Number, default: 80 },
        low: { type: Number, default: 20 }
      }
    },
    wifi: {
      ssid: { type: String },
      password: { type: String },
      signalStrength: { type: Number }
    },
    mqtt: {
      server: { type: String, default: 'mqtt://localhost:1883' },
      username: { type: String },
      password: { type: String }
    }
  }
}, {
  timestamps: true,
});

// 创建索引
deviceSchema.index({ userId: 1 });
deviceSchema.index({ deviceId: 1, userId: 1 });

// 检查模型是否已经存在，如果存在则使用现有模型
export const Device = mongoose.models.Device || mongoose.model<IDevice>('Device', deviceSchema); 